<?php
include('init.php');
$act = isset($_REQUEST['act'])?$_REQUEST['act']:'';
switch($act)
{
	case 'save':
		//update account balance
		$assignTable = array();
		foreach($_REQUEST as $reName=>$reValue)
		{
			preg_match('/^assign_mount_(\d)/',$reName,$match);
			if(count($match) == 2)
			{
				$assignTable[$_REQUEST['CACHE_ACCOUNT_TABLE'][$match[1]][DBC_ACCOUNT_ID]] = $reValue;
			}
		}
		//update self account
		$loginAccountID = SessionUtil::getVar(SESSION_KEY_LOGIN_ID);
		$_REQUEST['CACHE_ACCOUNT_TABLE'][$loginAccountID][DBC_ACCOUNT_BALANCE] += $_REQUEST['mount'] - $assignTable[$loginAccountID];
		$db = AppMain::getDbDriver();
		$db->updateSetWhere(DB_TABLE_NAME_ACCOUNT,array(DBC_ACCOUNT_BALANCE => $_REQUEST['CACHE_ACCOUNT_TABLE'][$loginAccountID][DBC_ACCOUNT_BALANCE]), new SimpleWhereClause(DBC_ACCOUNT_ID, '=', $loginAccountID));
		//update other
		foreach($assignTable as $accountID=>$reValue)
		{
			if($accountID == $loginAccountID)
				continue;
			$_REQUEST['CACHE_ACCOUNT_TABLE'][$accountID][DBC_ACCOUNT_BALANCE] -= $reValue;
			$db->updateSetWhere(DB_TABLE_NAME_ACCOUNT,array(DBC_ACCOUNT_BALANCE => $_REQUEST['CACHE_ACCOUNT_TABLE'][$accountID][DBC_ACCOUNT_BALANCE]), new SimpleWhereClause(DBC_ACCOUNT_ID, '=', $accountID));
		}
		$currentData = AppMain::getCurrentTime();
		$strTokenList = preg_split("/-/",$currentData);
		$logDir = constant('LOG_DATA_DIR').'/'.$strTokenList[0].'/'.$strTokenList[1].'/'.$strTokenList[2];
		if(!file_exists($logDir))
		{
			mkdir($logDir,0755,true);
		}
		$seperater1 = constant('SEPERATER_1');
		$seperater2 = constant('SEPERATER_2');
		$seperater3 = constant('SEPERATER_3');
		
		$logFile = $logDir.'/'.time('His').'_'.Util::makeRandomStr(3).'.html';
		$content = '';
		$content .= $seperater1.'<br>';
		$content .= 'Date:'.$_REQUEST['date']."<br>";
		$content .= $seperater2.'<br>';
		$content .= 'Total:'.$_REQUEST['mount']."<br>";
		$content .= $seperater2.'<br>';
		$content .= "Detail:<br>";
		$content .= nl2br($_REQUEST['detail'])."<br>";
		$content .= $seperater2.'<br>';
		$content .="Assign Info:<br>";
		foreach($assignTable as $accountID=>$reValue)
		{
			$content .= $_REQUEST['CACHE_ACCOUNT_TABLE'][$accountID][DBC_ACCOUNT_NAME].':'.$reValue."<br>";
		}
		$content .= $seperater2.'<br>';
		$content .= "User:".$_REQUEST['CACHE_ACCOUNT_TABLE'][$loginAccountID][DBC_ACCOUNT_NAME]."<br>";
		$content .= "Add Date:".$currentData.'<br>';
		
		$content .= $seperater3.'<br>';
		global_load_account_info_to_request();
		$content .="Account Balance:<br>";
		foreach($_REQUEST['CACHE_ACCOUNT_TABLE'] as $tmpData)
		{
			$content .= $tmpData[DBC_ACCOUNT_NAME].':'.$tmpData[DBC_ACCOUNT_BALANCE].'<br>';
		}
		
		$content .= $seperater1.'<br>';
		file_put_contents($logFile,$content);
		//send out mail
		foreach($assignTable as $accountID=>$reValue)
		{
			//$headers= "From:$from\r\n";
			$headers = "Content-type:text/html;charset=utf-8" . "\r\n";
			$subject = 'Simple Finace System '.$currentData;
			mail($_REQUEST['CACHE_ACCOUNT_TABLE'][$accountID][DBC_ACCOUNT_EMAIL], $subject, $content, $headers);
		}
		 header('Location:index.php');
		 exit();
	break;
}

$account_list = $_REQUEST['CACHE_ACCOUNT_TABLE'];
?>
<?php include 'header.php' ?>
<?php include 'index_top.php' ?>


<script language="javascript" src="js/formvalidate.js"></script>
<script language="javascript" src="js/jquery-ui-datepicker.min.js"></script>
<script language="javascript">
$(function(){
	$('.date').datepicker({ dateFormat: 'yy-mm-dd' });
	$('input[name=mount]').bind('validate_complete',assignAmountToAccount);
});

function assignAmountToAccount()
{
//divide amount equal to each account
		var total = parseFloat($('input[name=mount]').val(),10);
	
		$('.adddiv .assign input').each(function(i,inputObj){
			var currAccId = $(inputObj).attr('name');
			var strTokens = currAccId.split('_');
			currAccId = strTokens[strTokens.length - 1];
			var assignPercent = getAccountAssignPercent(currAccId);
			
				var eachAssignValue = 0;
				if(!isNaN(total))
				{
					eachAssignValue = total * assignPercent;
					eachAssignValue = eachAssignValue * 100;
					eachAssignValue = Math.round(eachAssignValue);
					eachAssignValue = eachAssignValue / 100;
				}
			$(inputObj).val(eachAssignValue);
		});
}
function checkFormValue(form)
{
	var total = parseFloat($('input[name=mount]').val(),10);
	if(isNaN(total) || total == 0)
	{
		alert("请输入金额");
		return false;
	}
	var eachSum = 0;
	$('.adddiv .assign input').each(function(i,inputObj){
		eachSum += parseFloat($(this).val(),10);
	});
	if(Math.abs(total - eachSum) > 0.1)
	{
		alert("金额总额与分配相差超过 0.1.");
		return false;
	}
	form.submit();
	return false;
}

$(function(){
	$('input[name=mount]').attr('disabled',true);
	initNumberPicker();
	$('input[name=mount]').attr('disabled',false);
	
	$('.mutiplePicker').bind('change',assignAmountToAccount);
});
function initNumberPicker()
{
	$('.mutiplePicker').css('float','none');
	var maxNumber = 11;
	for(i=1; i < maxNumber; i++)
	{
		var newOptionItem = '<option value="'+i+'">'+i+'</option>';
		$('.mutiplePicker').append(newOptionItem);
	}
	
	setTimeout(timeoutSelectValIE6,1);
}
function timeoutSelectValIE6()
{
	//selete the default value
	$('.mutiplePicker').each(function(i,v){
		var initDefaultVal = $(v).attr('data');
		//$(v).find('option[value='+initDefaultVal+']').attr('selected',true);
	});
}
function getAccountAssignPercent(accountid)
{
	var aPercent = 0;
	var totalMultipleNumer = 0;
	var accountMultipleNumber = 0;
	$('.mutiplePicker').each(function(i,v){
			var intVal = parseInt($(v).val(),10);
			totalMultipleNumer += intVal;
			var currAccId = $(v).attr('id');
			var strTokens = currAccId.split('_');
			currAccId = strTokens[strTokens.length - 1];
			
			if(currAccId == accountid)
			{
				accountMultipleNumber = intVal;
			}
	});
	
	if(totalMultipleNumer > 0)
		aPercent = accountMultipleNumber/totalMultipleNumer;
		
	return aPercent;
}
</script>
<form method="post">
<input type="hidden" name="act" value="save"/>
<div class="adddiv">
	<label>日期</label>
	<input name="date" class="date" value="<?php echo AppMain::getCurrentTime();?>"/>
	<label>金额</label>
	<input name="mount" class="_validate_form_float"/>
	<label>分配</label>
	<div class="assign">
		<ul>
		<?php foreach($account_list as $tmpData):?>
			<li><?php echo $tmpData[DBC_ACCOUNT_NAME];?>:&nbsp;&nbsp;<input class="_validate_form_float" name="assign_mount_<?php echo $tmpData[DBC_ACCOUNT_ID];?>"/>&nbsp;&nbsp;<select id="assign_mount_number_<?php echo $tmpData[DBC_ACCOUNT_ID];?>" class="mutiplePicker" data="<?php echo $tmpData[DBC_ACCOUNT_MULTIPLE];?>"></select></li>
		<?php endforeach;?>
		</ul>
	</div>
	<label>备注</label>
	<textarea name="detail"></textarea>
	<label></label>
	<input type="button" value="Save" class="button" onclick="return checkFormValue(this.form);"/>
</div>
</form>
<?php include 'footer.php' ?>